// promise

isCanPromise = true;

const promise = new Promise((resolve, reject) => {
  if (isCanPromise) {
    const gife = {
      price: "￥12000",
      name: "iphone 13 plus",
    };

    resolve(gife);
  } else {
    const erro = new Error("加班去了，忘记了");

    reject(erro);
  }
});

// promise
//   .then((obj) => {
//     console.log(obj);
//   })
//   .catch((err) => {
//     console.log(err.message);
//   });

// 手写promise
// 创建基本结构
function myPromise(excutor) {
  let self = this;
  self.statu = "pening"; //状态
  self.value = null; //成功后返回的值
  self.reason = null; //失败的原因
  //  暂存区
  self.onFulfilledCallBacks = [];
  self.onRejectedCallBacks = [];

  //   成功后返回的结果
  const resolve = (value) => {
    if (self.statu === "pening") {
      self.value = value;
      self.statu = "fulfilled";
      //   状态改变后将暂存区的东西依次取出
      self.onFulfilledCallBacks.forEach((item) => item(value));
    }
  };
  //   返回失败的原因
  const reject = (reason) => {
    if (self.statu === "pening") {
      self.reason = reason;
      self.statu = "rejected";
      //   状态改变后将暂存区的东西依次取出
      self.onRejectedCallBacks.forEach((item) => item(reason));
    }
  };
  // 4 立即执行
  excutor && excutor(resolve, reject);
}

// then
myPromise.prototype.then = function (onFulfilled, onRejected) {
  onFulfilled =
    typeof onFulfilled === "function" ? onFulfilled : (data) => resolve(data);
  onRejected =
    typeof onRejected === "function"
      ? onRejected
      : (err) => {
          throw err;
        };

  let self = this;
  if (self.statu === "pening") {
    self.onFulfilledCallBacks.push(onFulfilled);
    self.onRejectedCallBacks.push(onRejected);
  }
};

// 初级调用
const demo = new myPromise((resolve, reject) => {
  console.log("123");
  setTimeout(() => {
    resolve(222);
  }, 2000);
});

demo.then((data) => {
  console.log(data);
});
